<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!--工具条组件-->
      <page-tools :text="`当前共有${total}条记录`">
        <el-button
          size="small"
          type="danger"
          :disabled="!checkBtnPermission('employee_import')"
          @click="$router.push('/import?type=user')"
        >Excel导入
        </el-button>
        <el-button
          size="small"
          type="warning"
          :disabled="!checkBtnPermission('employee_export')"
          @click="exportFn1"
        >普通表头Excel导出
        </el-button>
        <el-button
          size="small"
          type="success"
          :disabled="!checkBtnPermission('employee_export')"
          @click="exportFn2"
        >复杂表头Excel导出
        </el-button>
        <el-button
          size="small"
          type="primary"
          :disabled="!checkBtnPermission('employees_add')"
          @click="$refs.addEmp.dialogShow = true"
        >新增员工
        </el-button>
      </page-tools>
      <!--表格组件-->
      <el-card>
        <el-table :data="tableData" border stripe @selection-change="selectionChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column type="index" label="序号" width="180" sortable=""/>
          <el-table-column prop="username" label="姓名" width="180" sortable=""/>
          <el-table-column label="头像" sortable="">
            <template slot-scope="scope">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="scope.row.staffPhoto"
                style="height: 60px"
                alt=""
                @click="showCode(scope.row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" width="180" sortable=""/>
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable=""
            :formatter="formatterFn"
          />
          <el-table-column prop="departmentName" label="部门" sortable=""/>
          <el-table-column v-slot="scope" prop="timeOfEntry" label="入职时间" sortable="">
            {{ scope.row.timeOfEntry | formatDate }}
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                :disabled="!checkBtnPermission('employee_eidt')"
                @click="$router.push('/employees/detail/'+scope.row.id)"
              >查看
              </el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="setRole(scope.row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delRole(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          :current-page.sync="queryData.page"
          :page-sizes="[10, 20, 40, 80]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="sizeChange"
          @current-change="pageChange"
        />
      </el-card>
      <!--新增员工弹窗-->
      <add-employees ref="addEmp" @updateList="initData"/>
      <!--图片二维码弹框 -->
      <el-dialog title="预览二维码" :visible.sync="dialogCodeShow">
        <!-- 存放一个canvas画布标签 -->
        <canvas id="canvas" style="display: block; margin: 0 auto"/>
      </el-dialog>
      <!--设置角色弹窗-->
      <set-role ref="setRole"/>
    </div>
  </div>
</template>

<script>
import { deleteEmployeesApi, getEmployeesListApi } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployees from '@/views/employees/components/addEmployees.vue'
import { formatDate } from '@/filters'
import QRCode from 'qrcode'
import SetRole from '@/views/employees/components/setRole.vue'

export default {
  name: 'Employees',
  components: { SetRole, AddEmployees },
  data() {
    return {
      dialogCodeShow: false,
      // 表格数据
      tableData: [],
      // 表格接口参数
      queryData: {
        page: 1,
        size: 10
      },
      // 总数
      total: 0,
      // 选中的数据
      selectData: []
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // 设置角色
    async setRole(id) {
      // 获取角色列表
      await this.$refs.setRole.getAllRoleList()
      // 获取当前员工角色
      await this.$refs.setRole.getCurrentRole(id)
      // 打开弹窗
      this.$refs.setRole.dialogShow = true
    },
    // 显示二维码弹框
    showCode(url) {
      if (!url) return
      this.dialogCodeShow = true // 设置为true了，弹框里面内容并没有渲染好，所有获取DOM是无法获取到的
      this.$nextTick(() => {
        var canvas = document.getElementById('canvas')
        // QRCode.toCanvas(画布标签DOM节点，转成二维码的内容，回调函数)
        QRCode.toCanvas(canvas, url, function(error) {
          if (error) console.error(error)
          console.log('success!')
        })
      })
    },
    // 获取员工列表数据
    async initData() {
      const { total, rows } = await getEmployeesListApi(this.queryData)
      this.tableData = rows
      this.total = total
    },
    // 分页
    pageChange(page) {
      this.queryData.page = page
      this.initData()
    },
    // 每页条数
    sizeChange(size) {
      this.queryData.size = size
      this.initData()
    },
    // 聘用形式
    formatterFn(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === +cellValue)
      return obj ? obj.value : '未知'
    },
    // 删除
    async delRole(id) {
      try {
        await this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return console.log('已取消删除', e)
      }
      await deleteEmployeesApi(id)
      this.$message.success('删除成功')
      // 边缘问题
      if (this.tableData.length === 1 && this.queryData.page > 1) {
        this.queryData.page--
      }
      await this.initData()
    },
    // 普通表头Excel导出
    exportFn1() {
      console.log('普通表头Excel导出')
      // 1. 按需加载导出的Excel模块文件
      import('@/vendor/Export2Excel').then(async excel => {
        // console.log(data)
        // 2. 获取需要导出的数据
        const { rows } = await getEmployeesListApi({
          page: 1,
          size: 100000000
        })
        // 3. 处理数据
        const res = this.generateData(rows)
        // 4. 利用excel模块,进行调用方法导出
        excel.export_json_to_excel({
          header: res.headerKey, //! 表头 必填
          data: res.bodyData, //! 具体数据 必填
          filename: '员工数据', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 处理数据过程
    generateData(data) {
      console.log(data)
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const headerKey = Object.keys(headers)
      console.log(headerKey)
      const result = []
      data.forEach(item => {
        const row = []
        headerKey.forEach(key => {
          // 处理时间格式
          if (headers[key] === 'formOfEmployment') {
            const info = EmployeeEnum.hireType.find(obj => obj.id === +item[headers[key]])
            row.push(info ? info.value : '未知')
          } else if (['timeOfEntry', 'correctionTime'].includes(headers[key])) {
            row.push(formatDate(item[headers[key]]))
          } else {
            row.push(item[headers[key]])
          }
        })
        result.push(row)
      })
      // console.log(result)
      // 返回一个对象
      return {
        headerKey,
        bodyData: result
      }
    },
    // 表格勾选事件
    selectionChange(val) {
      console.log('表格勾选事件', val)
      this.selectData = val
    },
    // 复杂表头导出
    async exportFn2() {
      const excel = await import('@/vendor/Export2Excel')
      if (!this.selectData.length) {
        return this.$message.warning('请先勾选需要导出的数据')
      }
      const res = this.generateData(this.selectData)
      // console.log(res)
      // 调用excel导出文件
      excel.export_json_to_excel({
        header: res.headerKey, //! 表头 必填
        multiHeader: [['基本信息', '', '', '', '', '', '部门']], //! 复杂表头部分
        merges: ['A1:F1', 'G1:G2'], //! 合并单元格
        data: res.bodyData, //! 具体数据 必填
        filename: '员工数据', // 非必填
        autoWidth: true, // 非必填
        bookType: 'xlsx' // 非必填
      })
    }
  }
}
</script>

<style scoped>

</style>
